<?php
namespace Home\Controller;
use Think\Controller;
//use Home\ORG\Excel;
class UserController extends ExtendController{//要养成控制器名与数据库表名一致

	public function user(){
        $this->_cmd('_user_');
    }
/*调用模型的方法
    public function aaa(){
    	$model=D('User');
    	$aa=$model->text();
    	echo $aa;
    }
*/   
    public function _user_sendMail() {
    	return new \Home\Model\UserModel ();
    }
 /*   
    //发送邮件按钮
    protected  function _user_sendMail(){//使用的是Common文件下的function、phpmailer、smtp文件
//      调用其他文件类的方法（文件名必须和类名一致）
//     	import("Home.Common.Pub");
//     	$Pub = new \Pub();
//     	$Pub::sayHello();
    	$email = "simple.zheng@cifang.hk";//这是单个的发送
    	$result='哈哈，终于成功了耶';
    	$aaa = smtp_mail($email,date('Y-m-d').'入库单',$result);//(直接调用Common/function文件的方法smtp_mail)
    	if($aaa){
    		$r=array('success'=>true,'msg'=>"发送成功");
    		$this->ajaxRespond($r);
    	}
    	else{
    		$r=array('success'=>false,'msg'=>"发送失败");
    		$this->ajaxRespond($r);
    	}
    }*/
    //从数据库得到用户的所有列表	
    protected function _user_list(){
       $way=i('post.way');
       $start=I('post.start',0,'intval');
       $limit=I('post.limit',20,'intval');
       $condition=array();
       $textValue=trim(I('post.textField'));
       if($textValue){
       	    $condition[]="name='$textValue'";
       }
       $sex=I('post.sex');
       if($sex){
       	    $condition[]="sex='$sex'";
       }
       $beginTime=I('post.beginTime',false,trim);
       $endTime=I('post.endTime',false,trim);
       if($beginTime){
       	    $beginTime=strtotime($beginTime);
       		$condition[]="register_time>='$beginTime'";
       		if($endTime){
       			$endTime=strtotime($endTime);
       			$condition[]="register_time<= '$endTime'";
       		}
       }
       $condition=implode('and ', $condition);//将数组变为字符串    
       if(empty($way) || $way=="search"){
       		$user=M('user')->where($condition)->limit($start,$limit)->order('register_time desc')->select();
      	 	$imgSrc="http://".$_SERVER["SERVER_NAME"].__ROOT__; //绝对路径http://localhost/messageTp
      	 	$imgSrc=$imgSrc."/Public/Data/Upload/userImg/";
      	 	foreach ($user as $k=>$v){
       	 		$user[$k]['name']='<span style="color:blue;font-size:14px;">'.$v['name'].'</span>';//这儿不能写成$v['name']，那样是无作用的
      	 		if($v["user_photo"]){
       				$user[$k]['user_photo']=$imgSrc.$v["user_photo"];//eg:http://localhost/messageTp/Public/Data/Upload/userImg/Jellyfish__thumb.jpg
      	 		}
      	 	}
      	 	$count = M('user')->where($condition)->count();
       		$this->ajaxRespond(array('data'=>$user,'total'=>$count));
       }
       else{
       	// 查询的结果集
       		$result=M('user')->field('name,email,sex')->where($condition)->order('register_time desc')->select();
       		$header=array();
      	 	$header[]=array("姓名","邮箱","性别");//插入表头
      	 	$excel=array_merge($header,$result);//合并数组
     	  	$fileDir="./Public/Data/csvFiles/";
       		if (!file_exists($fileDir)) {
       			mkdir($fileDir);
      	 	}
      	 	foreach($excel as $val){
       			// 插入csv
       			$inputStr = implode($val,",");
       			$fileName=$fileDir.date('Ymdhms').'.csv';//定义文件名
       			file_put_contents($fileName,$inputStr."\n",FILE_APPEND);//使用 FILE_APPEND 可避免删除文件中已有的内容。
       		}
       		$fileName="http://".$_SERVER["SERVER_NAME"].__ROOT__.$fileName;
       		$this->ajaxRespond(array('success'=>true,'fileName'=>$fileName));
       }
    }
 
    //添加用户
    protected function _user_addUser(){
    	//print_r($_FILES);exit;
    	$data =i('post.',array());
    	$name=$_FILES['upload']['name'];
    	$type=$_FILES['upload']['type'];
    	$tmp_name=$_FILES['upload']['tmp_name'];
    	$size=$_FILES['upload']['size'];
    	$fileDir="./Public/Data/Upload/userImg/";//控制器的地址是相对于入口文件index.php来写的
    	//ltrim($fileDir,".");
    	//explode(".", $string)
    	//echo $imgSrc;
    	//判断文件夹是否存在
    	if (!file_exists($fileDir)) {
    		mkdir($fileDir);
    	}
    	//图片地址.目标地址
    	$imgDir='';  
    	
    	if($name){
    		//1.判断格式   2.判断大小   3.判断是否是上传图片  is_upload_file  4.移动   5.移动失败$imgDir='';
    		$imgType=array(
    			"image/gif",	
    			"image/jpeg",
    			"image/pjpeg"		
    		);
    		if(in_array($type, $imgType)  && ($size < 2000000)){
    			if ($_FILES["upload"]["error"] > 0){	
    				echo "aaa";
    			}else{
    				$imgDir=$fileDir.$name;
    				$isSuccess=move_uploaded_file($tmp_name,$imgDir);
    				
    				//生成缩略图    				
    				$image = new \Think\Image(); 
    				$text=$image->open($imgDir);
    				//生成   Tulips.jpg   缩略图名应为Tulips_thumb.jpg
    				$na=explode(".", $name);
    				$na[0]=$na[0]."__thumb";
    				$name=implode(".", $na);
    				
     				$image->thumb(50,50,\Think\Image::IMAGE_THUMB_FILLED)->save($fileDir.$name);
     				
     				$imgDir=$fileDir.$name;
    				
    				$imgDir=substr($imgDir,1);
    				if(!$isSuccess){
    					$imgDir='';
    					echo "移动失败";
    				}
    			}
    		}
    	}
    	$data['registerTime']=time();
    	$user=M('user');
		$tmp=array(		    										
			'name'=>trim($data['name']),
			'password'=>$data['password'],
			'email'=>trim($data['email']),
			'sex'=>trim($data['sex']),
			'register_time'=>$data['registerTime'],
			'user_photo'=>$name
		);
		$result=$user->where(array(
			"email"=>$data['email']	
		))->find();
		if(empty($result['email'])){
			$result=$user->add($tmp);
			$this->ajaxRespond(array('success'=>1,"msg"=>"添加成功"));
		}
		$this->ajaxRespond(array('success'=>false,"msg"=>"该邮箱已注册..."));
    }
    
    //删除用户
    protected function _user_delUser(){
    	$userId=I('get.userId',0,'intval');
    	if($userId==0){
    		exit;
    	}
    	$user=D('user');
    	$result=$user->where("id='$userId'")->delete();
    	$photoName=$result[0]['user_photo'];//缩略图名字
    	$photo=explode('_', $photoName);
    	$name=$photo[0];
    	$condition[0]=$name;
    	$photo=explode('.', $photo[2]);
    	$jpg=$photo[1];
    	$condition[1]=$jpg;
    	$oriPhotoName=implode('.', $condition);//原本图片
    	$filename="./Public/Data/Upload/userImg/".$photoName;
    	$filesmallname="./Public/Data/Upload/userImg/".$oriPhotoName;
    	//检查图片文件是否存在
    	if(file_exists($filename) && file_exists($filesmallname)){ 
    		unlink($filename);//删除图片
    		unlink($filesmallname);
    	}
    	if(!empty($result)){
    		$this->ajaxRespond(array('success'=>true));
    	}
    	$this->ajaxRespond(array('success'=>false));
    }
    
    //编辑用户信息
    protected  function  _user_editorUser(){    	
    	$data = i('post.',array());
    	//print_r($data);
    	$pattern='/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/';
    	$nowValue=trim($data['nowValue']);
    	$originalValue=$data['originalValue'];
        $user=D('user');
    	$tmp=array(
    		'id'=>$data['id']
    	);
    	$result=$user->where($tmp)->where("name='$originalValue'OR email='$originalValue'OR sex='$originalValue'")->find();
    	if($result){
    		 if($result['name']==$originalValue){
    			$result=$user->where($tmp)->setField('name',$nowValue);
    		 }
     		 else if($result['email']==$originalValue){
     		 	if(!preg_match($pattern,$nowValue)){
     		 		$result=$user->where($tmp)->setField('email','....邮箱格式错误.....');
    			}else{
    				$condition=$user->where(array(
    					"email"=>$nowValue
    				))->find();
    				if(empty($condition)){
    					$result=$user->where($tmp)->setField('email',$nowValue);
    				}else{
    					$result=$user->where($tmp)->setField('email','....该邮箱已注册.....');
    				}
    			}
    		 }
    		 else{
    			$result=$user->where($tmp)->setField('sex',$nowValue);
    		 }
    	}
    }
    
    //删除按钮
    protected  function  _user_delButton(){
    	$userIds=I('get.userIds');
    	$userIds=explode(",",$userIds);
    	$map=array();
    	$map['id']= array('IN',$userIds);
    	$condition=D('user')->where($map)->select();
    	foreach($condition as $k=>$v){
    		$condition[$k]['user_photo']=$v['user_photo'];
    		$photoNameAll[]=$v['user_photo'];
    		if($v['user_photo']!=''){
    			$text=array();
    			$photoName=$v['user_photo'];//缩略图名字
    			$photo=explode('_', $photoName);
    			$nameUser=$photo[0];
    			$text[0]=$nameUser;
    			$photo=explode('.', $photo[2]);
    			$jpg=$photo[1];
    			$text[1]=$jpg;
    			$oriPhotoName=implode('.', $text);//原本图片
    			$filename="./Public/Data/Upload/userImg/".$photoName;
    			$filesmallname="./Public/Data/Upload/userImg/".$oriPhotoName;
    			//检查图片文件是否存在
    			if(file_exists($filename) && file_exists($filesmallname)){
    				unlink($filename);//删除图片
    				unlink($filesmallname);
    			}
    		}
    	}
    	//print_r($photoNameAll);
    	$result=D('user')->where($map)->delete();
    	
    }
    
    //上传、修改头像
    protected  function _user_uploadPho(){
    	$userIds=i('get.userIds');    	
    	$name=$_FILES['userPhoto']['name'];
    	$type=$_FILES['userPhoto']['type'];
    	$tmp_name=$_FILES['userPhoto']['tmp_name'];
    	$size=$_FILES['userPhoto']['size'];
    	$fileDir="./Public/Data/Upload/userImg/";
    	if (!file_exists($fileDir)) {
    		mkdir($fileDir);
    	}
    	$imgDir='';
    	if($name){
    		$imgType=array("image/gif","image/jpeg","image/pjpeg","image/png");
    		if(in_array($type, $imgType)  && ($size < 2000000)){
    			if ($_FILES["upload"]["error"] > 0){
    				echo "类型错误";
    			}else{
    				$imgDir=$fileDir.$name;
    				$isSuccess=move_uploaded_file($tmp_name,$imgDir);
    				//生成缩略图
    				$image = new \Think\Image();
    				$text=$image->open($imgDir);
    				//生成   Tulips.jpg   缩略图名应为Tulips_thumb.jpg
    				$na=explode(".", $name);
    				$na[0]=$na[0]."__thumb";
    				$name=implode(".", $na);
    				$image->thumb(50,50,\Think\Image::IMAGE_THUMB_FILLED)->save($fileDir.$name);
    				$imgDir=$fileDir.$name;    	
    				$imgDir=substr($imgDir,1);
    				if(!$isSuccess){
    					$imgDir='';
    					echo "移动失败";
    				}
    			};
    		}
    	}
    	$userIds=explode(",",$userIds);
    	$map=array();
    	$map['id']= array('IN',$userIds);
    	//找出用户已有的头像，进行删除
    	$condition=D('user')->where($map)->select();
    	foreach($condition as $k=>$v){
    		$condition[$k]['user_photo']=$v['user_photo'];
    		$photoNameAll[]=$v['user_photo'];
    		if($v['user_photo']!=''){
    			$text=array();
    			$photoName=$v['user_photo'];//缩略图名字
    			$photo=explode('_', $photoName);
    			$nameUser=$photo[0];
    			$text[0]=$nameUser;
    			$photo=explode('.', $photo[2]);
    			$jpg=$photo[1];
    			$text[1]=$jpg;
    			$oriPhotoName=implode('.', $text);//原本图片
    			$filename="./Public/Data/Upload/userImg/".$photoName;
    			$filesmallname="./Public/Data/Upload/userImg/".$oriPhotoName;
    			//检查图片文件是否存在
    			if(file_exists($filename) && file_exists($filesmallname)){
    				unlink($filename);//删除图片
    				unlink($filesmallname);
    			}
    		}
    	}
    	$data['user_photo']=$name;
    	$result=D('user')->where($map)->save($data);
    	if(!empty($result)){
    		$this->ajaxRespond(array('success'=>true));
    	}
    	$this->ajaxRespond(array('success'=>false));
    }
    
    //得到大头像的地址
    protected  function _user_getOriPhotoUrl(){
    	$userId=i('post.userId',0,'intval');
    	$user=M('user');
    	$condition=$user->where("id='$userId'")->select();
    	foreach($condition as $k=>$v){
    		$condition[$k]['user_photo']=$v['user_photo'];
    		$photoNameAll[]=$v['user_photo'];
    		if($v['user_photo']!=''){
    			$text=array();
    			$photoName=$v['user_photo'];//缩略图名字
    			$photo=explode('_', $photoName);
    			$nameUser=$photo[0];
    			$text[0]=$nameUser;
    			$photo=explode('.', $photo[2]);
    			$jpg=$photo[1];
    			$text[1]=$jpg;
    			$oriPhotoName=implode('.', $text);//原本图片
    			$filesmallname="http://".$_SERVER["SERVER_NAME"].__ROOT__."/Public/Data/Upload/userImg/".$oriPhotoName;
    		}
    	}
    	if(!empty($condition)){
    		$this->ajaxRespond(array('success'=>true,'imgOriUrl'=>"$filesmallname"));
    	}
    }
    
    //下载csv ,根据搜索结果进行下载
    protected function _user_downloadInfo(){
    	$condition=array();
		$textValue=I('get.textField',false,'trim');
		if($textValue){
			$condition[]="name='$textValue'";
		}
		$sex=I('get.sex');
		if($sex){
			$condition[]="sex='$sex'";
		}
		$beginTime=I('get.beginTime',false,'trim');
		$endTime=I('get.endTime',false,'trim');
		if($beginTime){
			$beginTime=strtotime($beginTime);
			$condition[]="register_time>='$beginTime'";
			if($endTime){
				$endTime=strtotime($endTime);
				$condition[]="register_time<= '$endTime'";
			}
		}
		// 根据条件查询
		$condition=implode('and ', $condition);
		// 查询的结果集
		$result=M('user')->field('name,email,sex')->where($condition)->order('register_time desc')->select();
		$header=array();
		$header[]=array("姓名","邮箱","性别");//插入表头
		$excel=array_merge($header,$result);//合并数组
		$fileDir="./Public/Data/csvFiles/";
		if (!file_exists($fileDir)) {
			mkdir($fileDir);
		}
		foreach($excel as $val){
			// 插入csv
			$inputStr = implode($val,",");
			$fileName=$fileDir.date('Ymdhms').'.csv';//定义文件名
			file_put_contents($fileName,$inputStr."\n",FILE_APPEND);//使用 FILE_APPEND 可避免删除文件中已有的内容。
		}
		$fileName="http://".$_SERVER["SERVER_NAME"].__ROOT__.$fileName;
		$this->ajaxRespond(array('success'=>true,'fileName'=>$fileName));
    }
    
    //需要打印的页面内容形成
    protected function _user_print(){
    	$id=$_GET['id'];
    	$attr=$_GET['attr'];
    	$number=$_GET['number'];
    	$text=$id.$attr.$number;
    	$StockcaseimgUrl="http://hittime.net:8080/erp/Codebar/html/image.php?filetype=PNG&dpi=72&scale=1&rotation=0&font_family=Arial.ttf&font_size=15&text=$text&thickness=30&checksum=&code=BCGcode128";
		echo "<img src='$StockcaseimgUrl'/>";
		//echo file_get_contents($StockcaseimgUrl);//读取内容
    }
    //store数据格式的形成
    protected function _user_excelList(){
    	$text=array(
    		array('number'=>'0','fieldName'=>'name'),
    	    array('number'=>'1','fieldName'=>'sex'),
    	    array('number'=>'2','fieldName'=>'email'),
    	);
    	$items=array('data'=>$text);
    	$result=json_encode($items);
    	echo $result;
    }
   
    protected function _user_export_template(){
    	$excel=array();
    	$excel[]=array("姓名","邮箱","性别","密码");//插入表头
    	$fileDir="./Public/Data/template/";
    	if (!file_exists($fileDir)) {
    		mkdir($fileDir);
    	}
    	foreach($excel as $val){
    		// 插入csv
    		$inputStr = implode($val,",");
    		$fileName=$fileDir.date('Ymdhms').'.csv';//定义文件名
    		file_put_contents($fileName,$inputStr."\n",FILE_APPEND);//使用 FILE_APPEND 可避免删除文件中已有的内容。
    	}
    	$fileName="http://".$_SERVER["SERVER_NAME"].__ROOT__.$fileName;
    	$this->ajaxRespond(array('success'=>true,'fileName'=>$fileName));
    }
    public function info(){
    	$userId=I("post.userId",0,'intval');
    	if($userId==0){
    		exit;
    	}
    	$result=D('user')->where("id='$userId'")->select();
    	$this->assign('result',$result);
    	$this->display("userInfo");
    }
    protected function _user_rightHtml(){
    	$userId=I("post.userId",0,'intval');
    	if($userId==0){
    		exit;
    	}
    	$result=D('user')->where("id='$userId'")->select();
        //print_r($result);
    	$this->assign('result',$result);
    	$this->display("rightHtml");//显示视图最重要的一点是 ：就是单打开视图链接，布局也是很完整的（先把html写好，再把要插入的信息嵌套进去）
    }
}